import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Row, Col, Button, Table, message, DatePicker, Select, Modal, Input } from 'antd'
import { UpOutlined, DownOutlined, DownloadOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import moment from 'moment'
import { addWindow } from '@redux/actions'
import style from '@pages/filingCaseManage/CaseManage.module.less'
import { getRoomListRequest, getListRequest, getArbitratorListRequest, getEmployeeListRequest } from './ajax'
import { awaitWrap, formatDate, strToNum } from '@js/tool'
import { json2Excel } from '@js/excel'

const { Item } = Form
const { Option } = Select
const { confirm } = Modal

const layout = {
  labelCol: { flex: '100px' }
}

function formatTime (l) {
  const arr = []
  l.begin_datetime = strToNum(l.begin_datetime)
  l.end_datetime = strToNum(l.end_datetime)
  if (l.begin_datetime) {
    arr.push(formatDate(l.begin_datetime, 'YYYY-MM-DD'))
    arr.push(`(${formatDate(l.begin_datetime, 'HH:mm')}`)
  }
  if (l.end_datetime) {
    arr.push(' ~ ')
    arr.push(formatDate(l.end_datetime, 'HH:mm'))
  }
  arr.push(')')
  return arr.join('')
}

function formatArbitrator (l) {
  const d = []
  if (l.arbitrator) {
    d.push(l.arbitrator)
  }
  if (l.arbitrator1) {
    d.push(l.arbitrator1)
  }
  if (l.arbitrator2) {
    d.push(l.arbitrator2)
  }
  return d.join('、')
}

// 获取表格字段配置
function getColumns () {
  return [
    {
      title: '序号',
      dataIndex: 'order',
      key: 'order',
      align: 'center',
      width: 60
    },
    {
      title: '案号',
      dataIndex: 'caseno_desc',
      key: 'caseno_desc'
    },
    {
      title: '庭室',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '时间',
      dataIndex: 'begin_datetime',
      key: 'begin_datetime',
      render: (v, l) => {
        return formatTime(l)
      }
    },
    {
      title: '庭室用途',
      dataIndex: 'use',
      key: 'use'
    },
    {
      title: '仲裁员',
      dataIndex: 'arbitrator',
      key: 'arbitrator',
      render: (v, l) => {
        return formatArbitrator(l)
      }
    },
    {
      title: '秘书',
      dataIndex: 'processer',
      key: 'processer'
    }
  ]
}

class SimpleSearch extends Component {
  state = {
    searchToggleBtn: false,
    loading: false,
    list: [],
    roomList: [],
    condition: [],
    arbitratorList: [],
    employeeList: [],
    visible: false,
    statusVisible: false,
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    }
  }

  formRef = React.createRef()

  getParams (form) {
    const { pagination } = this.state
    const { current, pageSize } = pagination
    form = form || this.formRef.current.getFieldsValue()
    const condition = []
    this.setState({ loading: true })
    if (form.caseno_desc) {
      condition.push({ k: 'caseno_desc', o: 'like', v: `%${form.caseno_desc}%` })
    }
    if (form.room) {
      condition.push({ k: 'hearingroomid', o: '=', v: form.room })
    }
    if (form.processerid) {
      condition.push({ k: 'processerid', o: '=', v: form.processerid })
    }
    if (form.arbitratorid) {
      condition.push({ k: 'arbitratorid|arbitratorid1|arbitratorid2', o: '=', v: form.arbitratorid })
    }
    if (form.beginTime) {
      const str = form.beginTime.format('YYYY-MM-DD')
      condition.push({ k: 'begin_datetime', o: '>=', v: Math.floor(moment(`${str} 00:00:00`).valueOf() / 1000) })
    }
    if (form.endTime) {
      const str = form.endTime.format('YYYY-MM-DD')
      const d = moment(`${str} 23:59:59`)
      condition.push({ k: 'end_datetime', o: '<=', v: Math.floor(d.valueOf() / 1000) })
    }
    this.setState({
      condition
    })
    delete form.beginTime
    delete form.endTime
    const data = {
      current,
      page_size: pageSize,
      condition: JSON.stringify(condition)
    }
    return data
  }

  // 获取案件数据
  async getTableData (form) {
    const { pagination } = this.state
    const { current, pageSize } = pagination
    const params = this.getParams(form)
    this.setState({ loading: true })
    const [e, d] = await awaitWrap(getListRequest(params))
    this.setState({ loading: false })
    if (e) {
      return message.warning(e.message)
    }
    if (d) {
      this.setState({
        list: d.list.map((li, i) => {
          li.order = pageSize * (current - 1) + i + 1
          return li
        }),
        pagination: {
          ...pagination,
          total: d.total
        }
      })
    }
  }

  // 表格请求变化
  tableChange ({ current, pageSize }, filters) {
    this.setState({
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getTableData()
    })
  }

  // 重置表格
  resetHandle () {
    this.formRef.current.resetFields()
    this.setState({
      condition: []
    })
    this.setState({
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  initFormByMeta () {
    const c = this.formRef.current
    const { formData = {} } = this.props.meta || {}
    c.resetFields()
    c.setFieldsValue(formData)
    c.submit()
  }

  async initRoomList () {
    const [e, d] = await awaitWrap(getRoomListRequest())
    if (e === null && d !== null) {
      this.setState({ roomList: d })
    }
  }

  async initArbitratorList () {
    const [e, d] = await awaitWrap(getArbitratorListRequest())
    if (e === null && d !== null) {
      this.setState({ arbitratorList: d.list })
    }
  }

  async initEmpolyeeList () {
    const [e, d] = await awaitWrap(getEmployeeListRequest())
    if (e === null && d !== null) {
      this.setState({ employeeList: d })
    }
  }

  // 二次弹框确认下载excel
  confirmDownload () {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: '您确定要导出excel吗？',
      onOk: () => {
        this.downloadExcel()
      }
    })
  }

  // 获取当前查询条件的全部数据，并下载excel
  async downloadExcel () {
    const current = 1
    const pageSize = 1000000
    const hide = message.loading('导出中', 300)
    const params = {
      current,
      page_size: pageSize,
      condition: JSON.stringify(this.state.condition)
    }
    const [e, d] = await awaitWrap(getListRequest(params))
    hide()
    if (e) {
      return message.warning(e.message)
    }
    if (d) {
      const list = d.list.map((l, i) => {
        return {
          序号: pageSize * (current - 1) + i + 1,
          案号: l.caseno_desc,
          庭室: l.name,
          时间: formatTime(l),
          庭室用途: l.use,
          仲裁员: formatArbitrator(l),
          秘书: l.processer,
          备注: l.remark
        }
      })
      json2Excel([{ data: list, sheetname: '全委开庭情况' }], '全委开庭情况')
    }
  }

  changeArbitrator (v) {
    const list = this.state.arbitratorList
    for (let i = 0; i < list.length; i++) {
      if (list[i].name === v) {
        this.formRef.current.setFieldsValue({ arbitratorid: list[i].id })
        break
      }
    }
  }

  changeProcesserid (v) {
    const list = this.state.employeeList
    for (let i = 0; i < list.length; i++) {
      if (list[i].name === v) {
        this.formRef.current.setFieldsValue({ processerid: list[i].id })
        break
      }
    }
  }

  componentDidUpdate (prev) {
    if (prev.meta !== this.props.meta) {
      this.initFormByMeta()
    }
  }

  componentDidMount () {
    this.initFormByMeta()
    this.initRoomList()
    this.initArbitratorList()
    this.initEmpolyeeList()
  }

  // 渲染搜索表单的展开和收起
  renderToggleBtns () {
    if (this.state.searchToggleBtn) {
      return (
        <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
          <span>展开</span>
          <UpOutlined />
        </Button>
      )
    }
    return (
      <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
        <span>收起</span>
        <DownOutlined />
      </Button>
    )
  }

  render () {
    const columns = getColumns.call(this)
    return (
      <div className={style.container}>
        <div className={style['title-line']}>
          <span>{this.props.title}</span>
        </div>
        <div className={style['search-container']}>
          <div className={style['search-form']}>
            <Form
              name='doc_seal_list' {...layout} ref={this.formRef} onFinish={v => {
                this.getTableData(v)
              }}
            >
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='开始时间' name='beginTime'>
                    <DatePicker className={style.full} placeholder='请选择日期' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='结束时间' name='endTime'>
                    <DatePicker className={style.full} placeholder='请选择日期' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='庭室' name='room'>
                    <Select placeholder='请选择' allowClear>
                      {this.state.roomList.map((li, i) => {
                        return (
                          <Option key={i} value={li.id}>{li.name}</Option>
                        )
                      })}
                    </Select>
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='案号' name='caseno_desc'>
                    <Input placeholder='请输入' allowClear />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item name='arbitratorid' noStyle><span /></Item>
                  <Item label='仲裁员姓名' name='arbitrator'>
                    <Select placeholder='请选择' allowClear showSearch onChange={(v) => this.changeArbitrator(v)}>
                      {this.state.arbitratorList.map((li, i) => {
                        return (
                          <Option key={i} value={li.name}>{li.name}</Option>
                        )
                      })}
                    </Select>
                  </Item>
                </Col>
                <Col span={8}>
                  <Item name='processerid' noStyle><span /></Item>
                  <Item label='秘书' name='processer'>
                    <Select placeholder='请选择' allowClear showSearch onChange={(v) => this.changeProcesserid(v)}>
                      {this.state.employeeList.map((li, i) => {
                        return (
                          <Option key={i} value={li.name}>{li.name}</Option>
                        )
                      })}
                    </Select>
                  </Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col span={24}>
                  <Item>
                    <div className={style['search-btns']}>
                      <Button type='primary' ghost htmlType='submit'>搜索</Button>
                      <Button htmlType='reset' onClick={() => this.resetHandle()}>重置
                      </Button>
                      {/* {this.renderToggleBtns()} */}
                    </div>
                  </Item>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
        <div className={style['download-btn-line']} style={{ marginBottom: '12px' }}>
          <Button type='primary' ghost onClick={() => this.confirmDownload()} icon={<DownloadOutlined />}>导出excel</Button>
        </div>
        <div className={style['table-container']}>
          <Table
            rowKey='id'
            loading={this.state.loading}
            columns={columns}
            dataSource={this.state.list}
            pagination={this.state.pagination}
            onChange={(...args) => this.tableChange(...args)}
          />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i))
  }
})

export default connect(mapState, mapDispatch)(SimpleSearch)
